import { PayOrder, TransOrder } from "../models/order";
import { flatten } from "../utils/index";

export default function order(app, opt, next) {
  app.post("/trans-order/delete", async (req) => {
    await TransOrder.deleteOne({ _id: req.body.id });
    return null;
  });
  app.post("/trans-order/add", async (req) => {
    const model = await TransOrder.insertOne(req.body);
    return model;
  });
  app.post("/trans-order/update", async (req) => {
    const { id, ...rest } = req.body;
    const model = await TransOrder.updateOne({ _id: id }, rest);
    return model;
  });
  app.post("/trans-order/from-excel", async (req, res) => {
    const { data } = req.body;
    const find = await TransOrder.find({
      sn: {
        $in: data.map((v) => v.sn),
      },
    }).select(["sn"]);
    const list = data.filter((v) => {
      return find.every((v2) => v2.sn != v.sn);
    });
    if (list.length != 0) {
      await TransOrder.insertMany(list);
    }

    return {
      successed: list.length,
      total: data.length,
      skiped: find.length,
    };
  });
  app.get("/trans-order/list", async (req, res) => {
    const { query } = req;
    const ps = [
      "sn",
      "ower",
      "from",
      "veh_model",
      "to",
      "customer",
      "veh_plate",
    ].filter((v) => query[v]);
    const resp = await res.createPagination(
      TransOrder,
      ps.reduce((acc, c) => {
        return {
          ...acc,
          [c]: {
            $regex: query[c],
            $options: "i",
          },
        };
      }, {})
    );
    const ids = resp.items.map((v) => v._id);

    const payOrders = await PayOrder.aggregate([
      {
        $project: {
          trans_orders: 1,
          remark: 1,
          existOrders: {
            $setIntersection: ["$trans_orders", ids],
          },
        },
      },
    ]);
    return {
      ...resp,
      payOrders: flatten(payOrders.map((v) => v.trans_orders)),
    };
  });
  app.post("/trans-order/check-pay", async (req, res) => {
    // 查询
    const find = await PayOrder.aggregate([
      {
        $project: {
          trans_order_ids: 1,
          remark: 1,
          existOrders: {
            $setIntersection: ["$trans_order_ids", req.body.ids],
          },
        },
      },
    ]);
    return find;
    const exist = flatten(find.map((v) => v.existOrders));
    if (exist.length) {
      throw new Error("存在已申请付款的运单，请重新选择");
    }

    return exist;
  });
  app.post("/trans-order/request-pay", async (req, res) => {
    const payOrder = new PayOrder(req.body);
    payOrder.status = 0;
    const user = await req.getUser();
    payOrder.user = user.name;
    await payOrder.save();
    return payOrder;
  });
  app.post("/trans-order/details", async (req, res) => {
    return TransOrder.find({
      _id: {
        $in: req.body.ids,
      },
    });
  });

  app.get("/pay-order/list", (req, res) => {
    return res.createPagination(PayOrder, {});
  });
  app.post("/pay-order/cancel", (req, res) => {
    return PayOrder.updateOne(
      { _id: req.body.id },
      {
        $set: { status: -1 },
      }
    );
  });
  app.post("/pay-order/pay", (req, res) => {
    return PayOrder.updateOne(
      { _id: req.body.id },
      {
        $set: { status: 1, pay_date: new Date() },
      }
    );
  });
  app.post("/pay-order/delete", (req, res) => {
    return PayOrder.deleteOne({ _id: req.body.id });
  });
  next();
}
